package com.example.springboot.modules.security.service.impl;

import cn.hutool.log.Log;
import com.example.springboot.common.utils.JwtUtil;
import com.example.springboot.common.utils.RedisUtis;
import com.example.springboot.globalutils.BizException;
import com.example.springboot.modules.mybatis.service.AccountsService;
import com.example.springboot.modules.security.controller.req.LoginUserReq;
import com.example.springboot.modules.security.entity.LoginUser;
import com.example.springboot.modules.security.service.LoginServcie;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
@Slf4j
public class LoginServcieImpl implements LoginServcie {
    @Autowired
    private AuthenticationManager authenticationManager; //认证管理器
    @Autowired
    private AccountsService accountsService;
    @Autowired
    private RedisUtis redisUtis;

    @Override
    public HashMap<String, String> login(LoginUserReq user) {
        //封装这样的对象才能进入管理器
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassWord());
        //通过认证管理器框架认证 (进入到自定义的认证userDetailsService)
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new BizException("用户名或密码错误");
        }
        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        log.info("loginUser = {}",loginUser);
        String userId = loginUser.getAccountsEntity().getAccountId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //authenticate存入redis
        redisUtis.setCacheObject("login: " + userId, loginUser);
        //把token响应给前端
        HashMap<String, String> map = new HashMap<>();
        map.put("token", jwt);
        return map;
    }
}
